import { Injectable } from '@nestjs/common';
import { Spec_Create_Dto, Spec_Update_Dto } from './assets/spec.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Spec } from './assets/spec.entity';
import { Repository } from 'typeorm';
import { util_Db_Add, util_Db_Delete, util_Db_PageList, util_Db_Update } from '@/common/util/db';
import { SpecsType_Service } from '../specsType/specsType.service';

@Injectable()
export class Spec_Service {
  constructor(
    @InjectRepository(Spec)
    private spec_Repository: Repository<Spec>,
    private specsType_Service: SpecsType_Service,
  ) {}
  async spec_Create(body: Spec_Create_Dto) {
    const specsType = await this.specsType_Service.specsType_FindOneById(body.specsTypeId);
    return await util_Db_Add({
      createDto: { ...body, specsType },
      repository: this.spec_Repository,
    });
  }

  async spec_FindByPage() {
    const queryBuilder = this.spec_Repository.createQueryBuilder('spec');
    return await util_Db_PageList<Spec>({ queryBuilder, query: {} });
  }

  async spec_FindBySpecsType(specsTypeId: number) {
    const queryBuilder = this.spec_Repository.createQueryBuilder('spec');
    return await util_Db_PageList<Spec>({ queryBuilder, query: { 'spec.specsTypeId': specsTypeId } });
  }

  async spec_Update(body: Spec_Update_Dto) {
    return await util_Db_Update({
      findOne: () => this.spec_FindOneById(body.id),
      updateDto: body,
      repository: this.spec_Repository,
    });
  }

  async spec_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.spec_FindOneById(id),
      id,
      repository: this.spec_Repository,
    });
  }

  async spec_FindOneById(id: number) {
    return await this.spec_Repository
      .createQueryBuilder('spec')
      .andWhere(`spec.id = :id`, { id: id })
      .getOne();
  }
}
